<?php

namespace app\user\controller\order;

use app\common\controller\Backend;
use app\common\controller\Frontend;
use think\facade\Db;

/**
 * 下单操作
 */
class Temp extends Frontend {
    /**
     * Order模型对象
     * @var object
     * @phpstan-var \app\admin\model\order\Order
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\user\model\order\Order;
    }


    /**
     * 生成临时订单
     */
    public function generateTempOrder() {
        $param = $this->request->param();
        Db::startTrans();
        try {
            $order = db::name('order')->where(['user_id' => $param['user_id']])->whereNull('out_trade_no')->find();
            if ($order) {
                $order_id = $order['id'];
            } else {
                $insert_order = [
                    'user_id' => $param['user_id'],
                ];
                $order_id = Db::name('order')->insertGetId($insert_order);
            }

            $insert_order_goods = [];
            foreach ($param['ids'] as $val) {
                $order_goods = Db::name('order_goods')->where(['goods_id' => $val])->whereNull('place_order_time')->find();
                if (!$order_goods) {
                    $insert_order_goods[] = [
                        'order_id' => $order_id,
                        'goods_id' => $val
                    ];
                }

            }
            if ($insert_order_goods) {
                db::name('order_goods')->insertAll($insert_order_goods);
            }

            db::commit();
        } catch (\Exception $e) {
            db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }


    /**
     * 临时订单列表
     */
    public function index(): void {

        $param = $this->request->param();
        //        print_r($param);die;
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        $order = db::name('order')->where(['user_id' => $this->auth->id, 'type' => $param['type']])->whereNull('place_order_time')->find();
        if (!$order) {
            $this->success('', [
                'list' => []
            ]);
        }

        $orderGoodsModel = new \app\admin\model\order\OrderGoods();

        $type = $param['type'];

        $res = $orderGoodsModel
            ->with(['brand', 'goods', 'orders' => function($query) use ($type){
                $query->where(['type' => $type]);
            }])
            ->whereNull('place_order_time')
            ->select()->toArray();



        foreach($res as $key => $val){
//            print_r($val);
            $res[$key]['goods']['price'] = number_format($val['goods']['price']);
            $res[$key]['goods']['supply_price'] = number_format($val['goods']['supply_price']);
            $res[$key]['purchase_price'] = number_format($val['purchase_price']);
        }

        $this->success('', [
            'list' => $res,
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 删除
     * @param array $ids
     * @throws Throwable
     */
    public function del(array $ids = []): void {

        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $where = [];
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $where[] = [$this->dataLimitField, 'in', $dataLimitAdminIds];
        }

        $orderGoodsModel = new \app\admin\model\order\OrderGoods();

        $pk = $orderGoodsModel->getPk();
        $where[] = [$pk, 'in', $ids];

        $count = 0;
        $data = $orderGoodsModel->where($where)->select();
        $orderGoodsModel->startTrans();
        try {
            foreach ($data as $v) {
                $count += $v->delete();
            }
            $orderGoodsModel->commit();
        } catch (Throwable $e) {
            $orderGoodsModel->rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}